package com.rf.richfitwheel.admin.iam.service.impl;

import com.rf.richfitwheel.admin.conf.IamPropertiesConfig;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.HttpEntityJsonUtil;
import com.rf.richfitwheel.admin.iam.dao.PortalRoleMemberMapper;
import com.rf.richfitwheel.admin.iam.model.*;
import com.rf.richfitwheel.admin.iam.service.PortalRoleMemberService;
import com.rf.richfitwheel.admin.sys.model.Config;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.common.utils.UuidUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hushouquan
 */
@Service
public class PortalRoleMemberServiceImpl implements PortalRoleMemberService{
    private Logger log = LoggerFactory.getLogger(PortalRoleMemberServiceImpl.class);
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    @Autowired
    private RestTemplate restTemplateOuter;
    @Autowired
    private ConfigService configService;
    @Autowired
    private PortalRoleMemberMapper portalRoleMemberMapper;
    /**
     * 从门户同步⽤户⻆⾊关系数据并入库
     *
     * @param appId    在商网注册的集成编号
     * @param myDate   时间戳毫秒值
     * @param config 游标
     * @param countSyn 记录数
     */
    @Override
    public Integer roleMemberSynDo(String appId, long myDate, Config config, Integer countSyn) throws URISyntaxException, IOException{
        Map<String, Object> parameter = new HashMap<>();
        //数据同步的游标
//        Config config = configService.getParamVlueByKey("IAM_ROLE_MEMBER_SYNC_CURSOR");
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("hostname", iamPropertiesConfig.getHostnameByAppId(appId));
        CloseableHttpResponse response = HttpEntityJsonUtil.executeApi(iamPropertiesConfig.getAccessKeyByAppId(appId),
                iamPropertiesConfig.getSecretKeyByAppId(appId), appId, "GET", null, headerMap,
                iamPropertiesConfig.getUrl() + UrlConstant.IAM_API_ROLE_MEMBER_SYNC, config.getParamValue());
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if(statusCode == org.apache.http.HttpStatus.SC_OK){
            IamReturnRoleMember iamReturnRoleMember = HttpEntityJsonUtil.httpEntityContentToJsonArray(entity, IamReturnRoleMember.class);
            if(iamReturnRoleMember != null && iamReturnRoleMember.getCode() == 0){
                PortalRoleMemberSyn portalRoleMemberSyn = iamReturnRoleMember.getData();
                List<PortalRoleMember> list = portalRoleMemberSyn.getRecords();
                for(PortalRoleMember portalRoleMember : list){
                    portalRoleMember.setId(UuidUtil.get32UUID());
                    portalRoleMember.setMyTime(myDate);
                    portalRoleMemberMapper.insert(portalRoleMember);
                }
                countSyn = countSyn + list.size();
                log.info("已同步{}条⽤户⻆⾊关系数据", countSyn);
                config.setParamValue(portalRoleMemberSyn.getNext_cursor() + "");
//                UserVO user = new UserVO();
//                user.setId("1");
//                configService.update(config, user);
                //如果还有记录的话递归继续执行
                if(portalRoleMemberSyn.isHas_more()){
                    countSyn = roleMemberSynDo(appId, myDate, config, countSyn);
                }
            }else{
                log.warn("调用门户同步⽤户⻆⾊关系数据失败：{}", iamReturnRoleMember);
            }
        }else{
            log.error("调用门户同步⽤户⻆⾊关系数据失败：{}", EntityUtils.toString(entity));
        }
        response.close();
        return countSyn;
    }
    
    /**
     * 在数据已同步入库的情况下将数据处理至正式表
     *
     * @param myDate 时间戳毫秒值
     */
    @Override
    public void roleMemberDeal(long myDate) throws Exception{
        PortalRoleMemberExample example = new PortalRoleMemberExample();
        PortalRoleMemberExample.Criteria criteria = example.createCriteria();
        criteria.andMyTimeEqualTo(myDate);
        List<PortalRoleMember> portalRoleMemberList = portalRoleMemberMapper.selectByExample(example);
        int count = 0;
        for(PortalRoleMember portalRoleMember : portalRoleMemberList){
            //TODO
            count++;
            if(count % 500 == 0 || count == portalRoleMemberList.size()){
                log.info("已处理{}/{}条数据", count, portalRoleMemberList.size());
            }
        }
    }
}
